<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\CompanyTrack;
use App\Models\Admin\Import;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Saas,Auth,DB,Log;

class CompanyTrackController extends AdminController
{
    use AdminTrait;

    protected $model;

    /**
     * 定义验证规则
     */
    protected $validate_rule = [
    ];

    /**
     * 定义验证错误信息
     */
    protected $err_msg = [
    ];

    /**
     * 定义列表排序
     */
    protected $orderBy = [
        'date' => 'desc',
        'id' => 'desc',
    ];

    protected $type = [
        CompanyTrack::TYPE_A => 'A类',
        CompanyTrack::TYPE_B => 'B类',
        CompanyTrack::TYPE_C => 'C类',
        CompanyTrack::TYPE_D => 'D类',
    ];

    public function __construct(CompanyTrack $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    protected function beforeIndex()
    {
        return [
            'track_type'=>$this->type,
        ];
    }

    protected function search($request)
    {
        $select = $this->model;
        ($liaisons = $request->query('liaisons','')) && $select = $select->where('liaisons','like',"%$liaisons%");
        ($username = $request->query('username','')) && $select = $select->where('username','like',"%$username%");
        if($mobile = $request->query('mobile','')){
            $select=$select->where('mobile',$mobile);
        }
        if($channel = $request->query('channel',''))
        {
            $select=$select->where('channel',$channel);
        }
        if($channel = $request->query('type',''))
        {
            $select=$select->where('type',$channel);
        }
        if($date = $request->query('date','')) {
            $time_arr = explode(',', $date);
//            list($start_time,$end_time)=date_assemble($time_arr[0],$time_arr[1]);
//            $end_time = $end_time-1;
            $select = $select->whereBetween('date',[$time_arr[0],$time_arr[1]]);
        }

        return $select;
    }

    public function info(Request $request)
    {
        $id = $request->query('id');
        $info = $this->model->getDetail($id);

        return $this->success(['info'=>$info]);
    }

    //导入客户跟踪
    public function importTrack(BaseRequest $request)
    {
        DB::beginTransaction();
        try {
            $file = $request->file;
            if (filesize($file) / 1024 / 1024 > 5) {
                return response()->json(['errcode' => 100, 'errmsg' => '数据大小超过5M,导入失败', 'list' => '']);
            }
            if ($file->getClientOriginalExtension() != 'xlsx') {
                return response()->json(['errcode' => 100, 'errmsg' => '文件格式不对,导入失败', 'list' => '']);
            }
            $list = Excel::toArray(new Import, $file);
            $head=['数据唯一编号','日期','对接人','客户类型','渠道','客户姓名','客户电话','地区','跟踪情况'];
            if($head!==array_filter($list[0][0])){
                return response()->json(['errcode'=>100,'errmsg'=>'模板表头字段不对,导入失败','list'=>'']);
            }
            unset($list[0][0]);
            $list = collect($list[0]);
            if (count($list) > 2001) {
                return response()->json(['errcode' => 100, 'errmsg' => '数据超过2000行,导入失败', 'list' => '']);
            }

            $error = $errmsg_arr = [];
            $list = $list->map(function ($val, $key) use (&$error) {
                if (count(array_filter($val))!=0) {
                    $val[9]=$key+1;
                    foreach ($val as $k1 => $value) {
                        if ($k1 > 9) {
                            unset($val[$k1]);
                        }
                        if (!$value && $k1 < 2) {
                            $error = ['errcode' => 100, 'errmsg' => '第' . $val[9] . '行未填写必填字段,导入失败', 'list' => ''];
                        }
                    }
                    return $val;
                }
            })->filter()->toArray();
            if (!empty($error)) return response()->json($error);

            $count = count($list);
            if (!$count) {
                return response()->json(['errcode' => 100, 'errmsg' => '导入数据为空', 'list' => '']);
            }
            foreach ($list as $val) {
                if (is_numeric($val[1])) {
                    $val[1] = date('Y-m-d', ($val[1] - 25569) * 24 * 3600);
                }
                $arr=[
                    'company_sn'=>$val[0],
                    'date'=>$val[1],
                    'liaisons'=>$val[2],
                    'type'=>$val[3],
                    'channel'=>$val[4],
                    'username'=>$val[5],
                    'mobile'=>$val[6],
                    'area'=>$val[7],
                    'track_info'=>$val[8],
                ];
                $track = CompanyTrack::where('company_sn', $val[0])->first();
                if ($track) {
                    $res=CompanyTrack::where('company_sn', $val[0])->update($arr);
                } else {
                    $arr['created_at'] = time();
                    $arr['updated_at'] = time();
                    $res=CompanyTrack::withoutGlobalScopes()->insert($arr);
                }

                $data = ['errcode'=>0,'msg'=>'第'.$val[9].'行的导入成功','count'=>$count,'num' =>$val[9]];
                if(!$res){
                    $errmsg_arr[] = $errmsg = '第'.$val[9].'行系统错误';
                    $data = ['errcode'=>100,'errmsg'=>$errmsg,'count'=>$count,'num' =>$val[9]];
                }
//                Log::INFO($data);
            }
            DB::commit();
            return response()->json(['errcode' => 0, 'msg' => '导入成功', 'errlist' => $errmsg_arr]);
        }catch(\Exception $exception){
            DB::rollback();
            return ['errcode' => 500, 'errmsg' => '导入失败', 'data' => ['err' => 'export_failed', 'errmsg' => $exception->getMessage()]];
        }
    }
}
